<?php

namespace app\index\controller;

use pay\Payservice;
use think\Controller;

class Pay extends Controller
{
    /**
     * 充值页面入口
     */
    public function order(){

      return $this->fetch();
    }

    public function payment(){
//        $input = input('post.');
        /*if($input['paytype'] == 'ali'){
            $data['payChannel'] = 'alipay';
        }else{
            $data['payChannel'] = 'wxpay';
        }*/
            $data['payId'] = config('pay.payid');
            $data['payChannel'] = 'alipay';
            $data['Subject'] = 'projectpay';
            $data['Money'] = 1;
            $data['orderNumber'] = $this->orderid();
            $data['attachData'] = cookie('uid');
            $data['Notify_url'] = "http://dk.zjsien.com/index/pay/url";
            $data['Return_url'] = "http://dk.zjsien.com/index/pay/url";
            $data['Sign'] = $this->signum($data);
//        接口地址
            $url = 'https://api.92pay.cn/core/api/request/pay/';
            $html = $this->curl($url,$data);
//        处理接口返回的html
            if($html){
            $pattrn = "/<img.*src=(\".*?\")/";
            preg_match($pattrn,$html,$match);
            $preg = trim($match[1],'"');
            return $preg;
            }else{
                return $this->result('',0,'充值失败');
            }

    }

    public function signum($data){
        $ispay = new Payservice(config('pay.payid'),config('pay.paykey'));
        return $ispay->sign($data);
    }

//    curl服务器发送请求
    public function curl($url,$data = null){
        $Url = $url;
        $postData = $data;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $Url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
        }
        $Data = curl_exec($curl);
        curl_close($curl);
        return $Data;
    }

    public function url(){
        $data = json_decode($_REQUEST,true);
        $ispay = new Payservice(config('pay.payid'),config('pay.paykey'));
        if($ispay->callbackSignCheck($data)){
//            可以在这里面处理是否保存到数据库
           $res = db('user')->where('id',$data['attchData'])->setInc('balance',$data['money']);
            return 'SUCCESS';
        }else{
            return 'ERROR';
        }
    }
    /**
     * 随机生成订单号
     */
    public function orderid(){
     return date('YmdHis') . str_pad(mt_rand(0, pow(10, 5) - 1), 5, '0', STR_PAD_LEFT);
    }


}
